<?php
/*
 * @Descripttion: 数据加密
 * @version: v1
 * @Author: Terry
 * @Date: 2021-10-06 15:05:59
 * @LastEditors: Terry
 */
declare (strict_types = 1);

namespace app\middleware;
use libs\AES;

class DataEncryption
{
    /*
     * 处理请求
     *
    * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next){
        $response = $next($request);
       // 从header里判断是否是json
        if ($_SERVER['SERVER_NAME']  == 'api.auxface.com' && method_exists($response, 'header') && in_array('application/json; charset=utf-8', $response->getHeader())) {
            $data = $response->getData();
            if($data['code']==0&&!empty($data['data'])){
                $puuid = $request->header('puuid') ?? '';
                $uuid = $request->header('uuid') ?? '';
                $secret = md5($puuid.$uuid);
                $iv  = substr($secret,0,16);
                $aes = new Aes($secret, 'AES-256-CBC', $iv,  0);  
                $data['data'] = base64_encode($aes->encrypt(json_encode($data['data'])));
            }
            $response = $response->data($data);
        }
        return $response;
    }
}
